package cn.myapps.demospringsecurity.manager;

import cn.myapps.demospringsecurity.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * AuthenticationSuccessHandler 是 Spring Security 中的一个核心接口，
 * 用于处理用户认证成功后的逻辑。当用户通过登录表单、OAuth2 授权码、
 * JWT Token 等方式成功认证后，系统会调用该接口的实现类，执行自定义的后续操作。
 */
@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        // 1. 从认证信息中获取用户名
        String username = authentication.getName();

        // 2. 生成 JWT Token
        String token = jwtUtil.genAccessToken(username);

        // 3. 将 Token 写入响应头或 Cookie
        response.setHeader("Authorization", "Bearer " + token); // 方式一：Header
        // 方式二：Cookie（推荐）
        /*
        Cookie cookie = new Cookie("jwtToken", token);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(7 * 24 * 60 * 60); // 7天
        cookie.setPath("/");
        response.addCookie(cookie);
        */

        // 4. 重定向到首页
        response.sendRedirect("/home");
    }

}
